<template>
  <div class="device-stats-card">
    <!-- 网关选择器 -->
    <el-card class="gateway-selector-card">
      <div class="table-header">
        <span>网关选择</span>
        <span style="font-size:12px;color:#888;">选择要查看的网关设备统计</span>
      </div>
      <el-radio-group v-model="selectedGatewayId" @change="onGatewayChange" class="gateway-radio-group">
        <el-radio-button 
          v-for="gateway in gatewayList" 
          :key="gateway.id" 
          :label="gateway.id"
          class="gateway-radio-btn"
        >
          {{ gateway.name }}-{{ gateway.ip }}
        </el-radio-button>
        <el-radio-button :label="0" class="gateway-radio-btn">
          全部网关
        </el-radio-button>
      </el-radio-group>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card total">
          <div class="stat-title">总设备数</div>
          <div class="stat-value">{{ currentStats.totalDevices }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card online">
          <div class="stat-title">在线设备</div>
          <div class="stat-value online">{{ currentStats.onlineDevices }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card offline">
          <div class="stat-title">离线设备</div>
          <div class="stat-value offline">{{ currentStats.offlineDevices }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card rate">
          <div class="stat-title">在线率</div>
          <div class="stat-value rate">{{ onlineRate }}%</div>
        </el-card>
      </el-col>
    </el-row>
    <el-card class="device-table-card">
      <div class="table-header">
        <span>设备状态列表</span>
        <span style="font-size:12px;color:#888;">数据实时推送，无需手动刷新</span>
      </div>
      <el-table :data="currentDeviceList" size="small" style="width: 100%; margin-top: 10px;">
        <el-table-column prop="gatewayName" label="所属网关" min-width="100" v-if="selectedGatewayId === 0" />
        <el-table-column prop="deviceId" label="设备ID" min-width="120" />
        <el-table-column prop="deviceName" label="设备名称" min-width="100" />
        <el-table-column prop="isOnline" label="状态" min-width="60">
          <template #default="scope">
            <el-tag :type="scope.row.isOnline ? 'success' : 'danger'">
              {{ scope.row.isOnline ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="offlineCount" label="掉线次数" min-width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.offlineCount > 0" type="warning">{{ scope.row.offlineCount }}</el-tag>
            <span v-else>0</span>
          </template>
        </el-table-column>
        <el-table-column prop="lastSeen" label="最后在线时间" min-width="160">
          <template #default="scope">
            {{ formatTime(scope.row.lastSeen) }}
          </template>
        </el-table-column>
        <el-table-column prop="offlineDuration" label="离线时长" min-width="100">
          <template #default="scope">
            <span v-if="!scope.row.isOnline && scope.row.lastSeen">
              {{ formatDuration(Date.now() - scope.row.lastSeen) }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="80">
          <template #default="scope">
            <el-button size="small" @click="resetOfflineCount(scope.row.deviceId)">重置</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card class="ranking-card">
      <div class="table-header">
        <span>掉线排行榜 (Top 10)</span>
        <span style="font-size:12px;color:#888;">按掉线次数排序</span>
      </div>
      <el-table :data="currentOfflineRanking" size="small" style="width: 100%; margin-top: 10px;">
        <el-table-column label="排名" min-width="60">
          <template #default="scope">
            <el-tag 
              :type="scope.$index === 0 ? 'danger' : scope.$index === 1 ? 'warning' : scope.$index === 2 ? 'info' : ''"
              size="small"
            >
              {{ scope.$index + 1 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="gatewayName" label="所属网关" min-width="100" v-if="selectedGatewayId === 0" />
        <el-table-column prop="deviceId" label="设备ID" min-width="120" />
        <el-table-column prop="deviceName" label="设备名称" min-width="100" />
        <el-table-column prop="offlineCount" label="掉线次数" min-width="80">
          <template #default="scope">
            <el-tag type="warning">{{ scope.row.offlineCount }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastOfflineTime" label="最近掉线时间" min-width="160">
          <template #default="scope">
            {{ formatTime(scope.row.lastOfflineTime) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import WebsocketIo from '../utils/websocket'
import { gatewayStore } from '../store/gateway'
import { storeToRefs } from 'pinia'

const API_BASE = '/api/device-stats'

// 使用网关store
const gateway_store = gatewayStore()
const { gatewayList } = storeToRefs(gateway_store)

// 选中的网关ID，0表示全部网关
const selectedGatewayId = ref(0)

// 所有网关的统计数据 - 按网关IP存储
const allGatewayStats = ref<{ [gatewayIp: string]: any }>({})

// 所有设备列表（包含网关信息）
const allDeviceList = ref<any[]>([])

let wsInstance: any = null
let handler: ((event: MessageEvent) => void) | null = null

// 计算属性：当前显示的统计数据
const currentStats = computed(() => {
  if (selectedGatewayId.value === 0) {
    // 全部网关的汇总统计
    const total = Object.values(allGatewayStats.value).reduce(
      (acc: any, stats: any) => ({
        totalDevices: acc.totalDevices + (stats.totalDevices || 0),
        onlineDevices: acc.onlineDevices + (stats.onlineDevices || 0),
        offlineDevices: acc.offlineDevices + (stats.offlineDevices || 0)
      }),
      { totalDevices: 0, onlineDevices: 0, offlineDevices: 0 }
    )
    return total
  } else {
    // 特定网关的统计 - 根据网关ID找到对应的IP
    const selectedGateway = gatewayList.value.find(g => g.id === selectedGatewayId.value)
    if (selectedGateway) {
      return allGatewayStats.value[selectedGateway.ip] || {
        totalDevices: 0,
        onlineDevices: 0,
        offlineDevices: 0
      }
    }
    return { totalDevices: 0, onlineDevices: 0, offlineDevices: 0 }
  }
})

// 计算属性：在线率
const onlineRate = computed(() => {
  const { totalDevices, onlineDevices } = currentStats.value
  if (totalDevices === 0) return '0'
  return ((onlineDevices / totalDevices) * 100).toFixed(1)
})

// 计算属性：当前显示的设备列表
const currentDeviceList = computed(() => {
  if (selectedGatewayId.value === 0) {
    return allDeviceList.value
  } else {
    // 根据网关ID找到对应的IP，然后过滤设备
    const selectedGateway = gatewayList.value.find(g => g.id === selectedGatewayId.value)
    if (selectedGateway) {
      return allDeviceList.value.filter(device => device.gatewayIp === selectedGateway.ip)
    }
    return []
  }
})

// 计算属性：当前显示的掉线排行榜
const currentOfflineRanking = computed(() => {
  const devices = currentDeviceList.value
    .filter(device => device.offlineCount > 0)
    .sort((a, b) => b.offlineCount - a.offlineCount)
    .slice(0, 10)
  return devices
})

function formatTime(ts: number) {
  if (!ts) return '-'
  const d = new Date(ts)
  return d.toLocaleString()
}

function formatDuration(ms: number) {
  if (!ms || ms < 0) return '-'
  const seconds = Math.floor(ms / 1000)
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes / 60)
  const days = Math.floor(hours / 24)
  
  if (days > 0) return `${days}天${hours % 24}小时`
  if (hours > 0) return `${hours}小时${minutes % 60}分钟`
  if (minutes > 0) return `${minutes}分钟${seconds % 60}秒`
  return `${seconds}秒`
}

function showOfflineNotification(event: any) {
  const notification = document.createElement('div')
  notification.className = 'offline-notification'
  notification.innerHTML = `
    <div class="notification-content">
      <strong>设备掉线警告</strong><br>
      设备 ${event.deviceId} 已掉线<br>
      网关IP: ${event.gatewayIp}<br>
      掉线时间: ${formatTime(event.offlineTime)}
    </div>
  `
  document.body.appendChild(notification)
  setTimeout(() => {
    notification.remove()
  }, 3000)
}

// 处理设备掉线事件
function handleDeviceOffline(data: any) {
  const { deviceId, gatewayIp, offlineTime } = data
  
  // 显示掉线通知
  showOfflineNotification({
    deviceId,
    gatewayIp,
    offlineTime
  })
  
  // 更新设备列表中对应设备的状态
  const deviceIndex = allDeviceList.value.findIndex(d => 
    d.deviceId === deviceId && d.gatewayIp === gatewayIp
  )
  
  if (deviceIndex !== -1) {
    const device = allDeviceList.value[deviceIndex]
    // 更新设备状态
    allDeviceList.value[deviceIndex] = {
      ...device,
      isOnline: false,
      lastSeen: offlineTime,
      lastOfflineTime: offlineTime,
      offlineCount: (device.offlineCount || 0) + 1
    }
    
    // 重新计算该网关的统计数据
    const gatewayDevices = allDeviceList.value.filter(d => d.gatewayIp === gatewayIp)
    const onlineDevices = gatewayDevices.filter(d => d.isOnline).length
    const totalDevices = gatewayDevices.length
    const offlineDevices = totalDevices - onlineDevices
    
    allGatewayStats.value[gatewayIp] = {
      totalDevices,
      onlineDevices,
      offlineDevices
    }
  }
  console.log(`设备 ${deviceId} (网关: ${gatewayIp}) 已掉线`)
}

// 网关切换事件处理
function onGatewayChange(gatewayId: number) {
  console.log('切换到网关:', gatewayId === 0 ? '全部网关' : `网关${gatewayId}`)
  // 可以在这里添加额外的逻辑，比如重新请求数据
}

function updateStatsFromPayload(payload: any) {
  console.log('DeviceStatsCard: 收到统计数据更新', payload)
  
  // 检查是否有设备详情数据（包括空数组的情况）
  if (payload.deviceDetails !== undefined) {
    console.log('DeviceStatsCard: 处理设备详情数据', payload.deviceDetails)
    
    // 如果设备详情为空数组，说明该网关下没有设备了
    if (payload.deviceDetails.length === 0) {
      // 从payload中获取网关IP信息，如果没有则从totalDevices等信息推断
      const gatewayIp = payload.gatewayIp || Object.keys(allGatewayStats.value)[0]
      
      if (gatewayIp) {
        // 清空该网关的统计数据
        allGatewayStats.value[gatewayIp] = {
          totalDevices: 0,
          onlineDevices: 0,
          offlineDevices: 0
        }
        
        // 从设备列表中移除该网关的所有设备
        allDeviceList.value = allDeviceList.value.filter(device => device.gatewayIp !== gatewayIp)
        
        console.log(`DeviceStatsCard: 已清空网关 ${gatewayIp} 的所有设备数据`)
      }
      return
    }
    
    // 先清空设备列表，防止模拟数据残留
    allDeviceList.value = []
    
    // 按网关IP分组设备
    const devicesByGateway = payload.deviceDetails.reduce((acc: any, device: any) => {
      const gatewayIp = device.gatewayIp
      if (!acc[gatewayIp]) {
        acc[gatewayIp] = []
      }
      acc[gatewayIp].push(device)
      return acc
    }, {})
    
    // 为每个网关更新统计数据
    Object.keys(devicesByGateway).forEach(gatewayIp => {
      const devices = devicesByGateway[gatewayIp]
      const onlineDevices = devices.filter((d: any) => d.isOnline).length
      const totalDevices = devices.length
      const offlineDevices = totalDevices - onlineDevices
      
      // 更新该网关的统计数据
      allGatewayStats.value[gatewayIp] = {
        totalDevices,
        onlineDevices,
        offlineDevices
      }
      
      // 找到对应的网关信息
      const gateway = gatewayList.value.find(g => g.ip === gatewayIp)
      const gatewayName = gateway?.name || `网关(${gatewayIp})`
      const gatewayId = gateway?.id || 0
      
      // 处理设备信息
      const devicesWithGateway = devices.map((device: any) => ({
        ...device,
        gatewayId,
        gatewayName,
        deviceName: device.deviceName || `监测点${device.deviceId}`,
        lastSeen: device.lastSeen, // 直接使用payload中的lastSeen
        lastOfflineTime: device.isOnline ? null : device.lastSeen
      }))
      
      // 添加新数据
      allDeviceList.value.push(...devicesWithGateway)
    })
  } else {
    // 如果没有设备详情，使用全局统计数据
    console.log('收到全局统计数据:', payload)
  }
}

// 生成模拟数据的函数
function generateMockData() {
  // 为每个网关生成模拟设备数据
  gatewayList.value.forEach(gateway => {
    const deviceCount = 12 // 每个网关12个设备
    const onlineCount = Math.floor(Math.random() * 4) + 8 // 8-12个在线
    const offlineCount = deviceCount - onlineCount
    
    // 使用网关IP作为key
    allGatewayStats.value[gateway.ip] = {
      totalDevices: deviceCount,
      onlineDevices: onlineCount,
      offlineDevices: offlineCount
    }
    
    // 生成设备详情
    const devices = []
    for (let i = 1; i <= deviceCount; i++) {
      const isOnline = i <= onlineCount
      const deviceOfflineCount = isOnline ? 0 : Math.floor(Math.random() * 10) + 1
      const lastSeen = isOnline ? Date.now() : Date.now() - Math.random() * 86400000 // 最多1天前
      
      devices.push({
        deviceId: `${gateway.id}-${String(i).padStart(2, '0')}`,
        deviceName: `监测点${i}`,
        gatewayId: gateway.id,
        gatewayName: gateway.name,
        gatewayIp: gateway.ip, // 添加gatewayIp字段
        isOnline,
        offlineCount: deviceOfflineCount,
        lastSeen,
        lastOnlineTime: lastSeen, // 添加lastOnlineTime字段
        lastOfflineTime: isOnline ? null : lastSeen
      })
    }
    
    // 移除该网关的旧数据，添加新数据
    allDeviceList.value = allDeviceList.value.filter(d => d.gatewayIp !== gateway.ip)
    allDeviceList.value.push(...devices)
  })
}

async function resetOfflineCount(deviceId: string) {
  try {
    const res = await fetch(`${API_BASE}/${deviceId}/reset-offline-count`, { method: 'POST' })
    const data = await res.json()
    if (data.success) {
      ElMessage.success('掉线计数已重置')
      nextTick(() => {
        WebsocketIo.getInstance().sendMessage(JSON.stringify({ action: 'getDeviceStats' }))
      })
    }
  } catch (e) {
    ElMessage.error('重置失败')
  }
}

onMounted(() => {

  // 主动请求统计数据
  WebsocketIo.getInstance().sendMessage(JSON.stringify({
    action: 'getDeviceStats'
  }))

  // 监听全局WebSocket消息事件
  const handleGlobalMessage = (event: CustomEvent) => {
    const data = event.detail
    if (!data || typeof data !== 'object') {
      return;
    }
    if (data.action === 'deviceStats' || data.action === 'deviceStatsUpdate') {
   
      updateStatsFromPayload(data.data || data)
    } else if (data.action === 'deviceOffline') {

      handleDeviceOffline(data.data || data)
    } else {
      console.log('DeviceStatsCard: 未匹配的消息类型:', data.action)
    }
  }
  
  // 监听全局WebSocket消息事件
  window.addEventListener('websocket-message', handleGlobalMessage as EventListener)
  
  // 保存事件处理器引用以便清理
  handler = handleGlobalMessage as any
})

onUnmounted(() => {
  if (handler) {
    window.removeEventListener('websocket-message', handler as EventListener)
  }
})
</script>

<style scoped>
.device-stats-card {
  max-width: 900px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.gateway-selector-card {
  margin-bottom: 0;
}

.gateway-radio-group {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.gateway-radio-btn {
  margin-right: 0 !important;
}
.stats-row {
  margin-bottom: 0;
}
.stat-card {
  text-align: center;
  padding: 12px 0;
}
.stat-title {
  font-size: 15px;
  color: #888;
}
.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin-top: 6px;
}
.stat-value.online {
  color: #13ce66;
}
.stat-value.offline {
  color: #ff4949;
}
.device-table-card {
  margin-top: 0;
}
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 4px;
}
.ranking-card {
  margin-top: 0;
}
.offline-notification {
  position: fixed;
  top: 20px;
  right: 20px;
  background: #f44336;
  color: white;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0,0,0,0.2);
  z-index: 1000;
  animation: slideIn 0.3s ease-out;
}
@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}
</style>